package com.tiancheng.trade.merchant.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tiancheng.trade.commom.core.data.Result;
import com.tiancheng.trade.merchant.service.IMerchantService;
import com.tiancheng.trade.merchant.util.BigDataRequest;
import com.tiancheng.trade.merchant.vo.merchant.CommonMerchantVO;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;


/**
 * @author kellen
 * @date 2021/7/16
 */
@RestController
@RequestMapping("/common")
public class CommonController {

    @Resource
    private BigDataRequest bigDataRequest;
    @Resource
    private IMerchantService merchantService;


    @RequestMapping(value = "/getCity")
    public Result getCity(String pid) {
        String api = "/global/city/sub";
        Map<String, Object> paramData = new TreeMap<String, Object>();
        paramData.put("id", pid);
        JSONObject jsonObject = bigDataRequest.postRequest(api, null, paramData);
        if (jsonObject != null && jsonObject.containsKey("list")) {
            JSONArray list = jsonObject.getJSONArray("list");
            list.forEach(e -> ((JSONObject) e).remove("airport"));
            return Result.success(list);
        }
        return Result.success();
    }

    /**
     * 手动触发任务
     *
     * @return
     */
    @GetMapping(value = "/getMerchantByCreateDate")
    public Result pushMerchant2OA(@RequestParam("date") String date) {
        LocalDate createDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        List<CommonMerchantVO> list=merchantService.getMerchantByCreateDate(createDate);
        return Result.success(list);
    }

    private void valid() {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes()))
                .getRequest();
        String userAgent = request.getHeader("user-agent");
        String remoteAddr = request.getRemoteAddr();
        if (!StrUtil.startWith(userAgent, "kube") || !StrUtil.startWith(remoteAddr, "10")) {
            throw new RuntimeException("无权访问该接口");
        }
    }
}
